package org.smarthings.mqtt;

import java.util.HashMap;

import org.eclipse.paho.client.mqttv3.IMqttDeliveryToken;
import org.eclipse.paho.client.mqttv3.MqttCallback;
import org.eclipse.paho.client.mqttv3.MqttMessage;
import org.smarthings.Callback;
import org.smarthings.Message;
import org.smarthings.Utils;

public class MqttCallbackImpl implements MqttCallback {
	private HashMap<String, Callback> callbacks = new HashMap<String, Callback>();

	public void addCallback(String topic, Callback callback) {
		callbacks.put(topic, callback);
	}

	public void connectionLost(Throwable cause) {
		// do nothing
	}

	public void messageArrived(String topic, MqttMessage message) throws Exception {
		String uri = Utils.normalizeUri(topic);
		Callback callback = callbacks.get(uri);
		if (callback != null) {
			callback.message(Message.createSimpleMessage(message.getPayload(), MqttFactory.PROTOCOL, uri, "application/json"));
		}
	}

	public void deliveryComplete(IMqttDeliveryToken token) {
		// do nothing
	}
}
